package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import pojo.*;
import service.StudentService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.*;
import java.net.URLEncoder;
import java.util.List;

import static sf.constant.DISPLAY_BLOCK;
import static sf.constant.DISPLAY_NONE;

/**
 * @author tao
 * @date 2021/11/10
 */

@Controller
@RequestMapping("/hms")
public class StudentController {


    @Autowired
    @Qualifier("studentServiceImpl")
    private StudentService studentService;

    //跳转到学生注册界面
    @RequestMapping("/StudentRegister")
    public String index1(){
        return "StudentRegister";
    }
    //跳转到学生登录界面
    @RequestMapping("/StudentLogin")
    public String index2(){
        return "StudentLogin";
    }

    @RequestMapping("/toStuAddClazz")
    public String index3(){
        return "student/addClazz";
    }

    @RequestMapping("/toStuUpdateWork/{id}")
    public String index4(@PathVariable("id")int id,Model model,HttpSession session){
        Work work = studentService.selectWorkBook(id);
        System.out.println("============================");
        System.out.println(work);
        model.addAttribute("work",work);
        model.addAttribute("workBookId",id);
        Student student = (Student) session.getAttribute("student");
        MyWork myWork = studentService.selectStudentWorkBook(id,student.getId());

        System.out.println(myWork+"+++++++++==");
        model.addAttribute("answer",myWork);
        return "student/selectWorkBook";
    }

    @RequestMapping("/studentAnswer/{sid}")
    public String studentAnswer(@PathVariable("sid")int wid, @RequestParam("file") CommonsMultipartFile file, HttpServletRequest request, MyWork work, HttpSession session){
        Student student = (Student) session.getAttribute("student");
        //获取文件名 : file.getOriginalFilename();
        String uploadFileName = file.getOriginalFilename();
        //如果文件名为空，直接回到首页！
        System.out.println("上传文件名 : "+uploadFileName);
        //==========多加一步创建，文件夹总是创建不成功===========
        String path1 = "D:/upload";
        File realPath1 = new File(path1);
        if (!realPath1.exists()){
            realPath1.mkdir();
        }
        //=================================================
        //上传路径保存设置
        String path = "D:/upload/"+student.getId()+"+"+student.getName();
        //如果路径不存在，创建一个
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }
        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        try {
            file.transferTo(new File(realPath +"/"+ uploadFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //将文件路径写入数据库
        if (!"".equals(uploadFileName)){
            work.setFileName(realPath+"\\"+uploadFileName);
        }
        System.out.println(work);
        studentService.submitJob(work);
        return "redirect:/hms/success";
    }

    @RequestMapping("/studentDownload/{workBookId}")
    public String downloads(@PathVariable("workBookId")int sid, HttpServletResponse response , HttpServletRequest request) throws Exception{
        //要下载的文件地址
        MyWork myWork = studentService.selectWork(sid);
        String fileName1 = myWork.getFileName();

        File fileP = new File(fileName1);
        String  fileName = fileP.getName();

        //1、设置response 响应头
        response.reset(); //设置页面不缓存,清空buffer
        response.setCharacterEncoding("UTF-8"); //字符编码
        response.setContentType("multipart/form-data"); //二进制传输数据
        //设置响应头
        response.setHeader("Content-Disposition",
                "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));

        //2、 读取文件--输入流
        InputStream input=new FileInputStream(fileP);
        //3、 写出文件--输出流
        OutputStream out = response.getOutputStream();

        byte[] buff =new byte[1024];
        int index;
        //4、执行 写出操作
        while((index= input.read(buff))!= -1){
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();
        return "";
    }

    //学生注册
    @RequestMapping("/stuReg")
    public String studentRegister(Model model,Student student){
        System.out.println(studentService.selectStudent(student.getId()));
        if (studentService.selectStudent(student.getId())==null) {
            model.addAttribute("display", DISPLAY_NONE);
            model.addAttribute("Register", "注册成功");
            studentService.addStudent(student);
            return "redirect:/hms/StudentLogin";
        }else {
            model.addAttribute("display", DISPLAY_BLOCK);
            model.addAttribute("Register", "学号已被注册");
            return "redirect:/hms/StudentRegister";
        }
    }

    //学生登录
    @RequestMapping("/stuLogin")
    public String studentLogin(Model model, Student student, HttpSession session){
        //由下面4个语句打印的结果可以看出，进行了两次查询
        if (studentService.selectStudent(student.getId())!= null) {
            if (student.getPassword().equals(studentService.studentPassword(student.getId()).getPassword())) {
                model.addAttribute("display", DISPLAY_NONE);
                model.addAttribute("Register", "登录成功");
                if (session.getAttribute("student")!=null){
                    return "redirect:/hms/success";
                }
                Student student1 = studentService.selectStudent(student.getId());
                student1.setPassword(null);
                session.setAttribute("student",student1);
                return "redirect:/hms/success";
            } else {
                model.addAttribute("display", DISPLAY_BLOCK);
                model.addAttribute("Register", "用户名或密码错误");
                return "redirect:/hms/StudentLogin";
            }
        }else {
            model.addAttribute("display", DISPLAY_BLOCK);
            model.addAttribute("Register", "学生用户名未注册");
            return "redirect:/hms/StudentLogin";
        }
    }

    //学生退出登录
    @RequestMapping("/stuLogout")
    public String logout(HttpSession session){
        //session过期
        session.invalidate();
        return "index";
    }

    //成功界面
    @RequestMapping("/success")
    public String success(Model model,HttpSession session){
        Student student = (Student) session.getAttribute("student");
        System.out.println(student.getId());
        List<Clazz> clazzes = studentService.myClazz(student.getId());
        model.addAttribute("clazz",clazzes);
        List<Work> works = studentService.myWork(student.getId());
        model.addAttribute("work",works);

        return "student/studentSystem1";
    }

    @RequestMapping("/outClazz/{id}")
    public String outClazz(@PathVariable("id")int id,HttpSession session){
        Student student = (Student) session.getAttribute("student");
        int i = studentService.outClazz(id,student.getId());
        System.out.println(i+"条===========");
        return "redirect:/hms/success";
    }

    @RequestMapping("/stuAddClazz")
    public String addClazz(Clazz clazz,HttpSession session){
        System.out.println(clazz);
        Student student = (Student) session.getAttribute("student");
        studentService.addClazz(clazz.getId(),student.getId());
        return "redirect:/hms/success";
    }

    

    @ResponseBody
    @RequestMapping("/studentClazz")
    public List<Clazz> studentClazz(int id){
        System.out.println(id);
        List<Clazz> clazzes = studentService.myClazz(id);
        for ( Clazz books:clazzes) {
            System.out.println(books);
        }
        return clazzes;
    }


}
